package com.lagou.tomcat.request;

import com.lagou.tomcat.container.Servlet;
import com.lagou.tomcat.mapper.MappedContext;
import com.lagou.tomcat.mapper.MappedHost;
import com.lagou.tomcat.mapper.MappedWrapper;
import com.lagou.tomcat.mapper.Mapper;
import com.lagou.tomcat.response.Response;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

/**
 * @author zhangjinshan
 * @version 1.0
 * @description
 * @date 2021/7/15 上午9:01
 */
public class RequestProcessor extends Thread{

    private Socket socket;

    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try{
            InputStream inputStream = socket.getInputStream();
            // 封装Request对象和Response对象
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            String url = request.getUrl();
            String host = request.getHost();
            if (url.lastIndexOf(".html") > -1){
                //静态资源处理
                String appBase = mapper.getHosts().get(host).getHost().getAppBase();
                response.outputHtml(appBase + url);
                socket.close();
            } else {
                //非静态资源处理
                Map<String, MappedHost> hosts = mapper.getHosts();
                MappedHost mappedHost = hosts.get(host);
                if (mappedHost == null) {
                    response.outputHtml(host + "404 Not Refund");
                    socket.close();
                    return;
                }
                String context = "/" + url.split("/")[1];
                MappedContext mappedContext = mappedHost.getContexts().get(context);
                if (mappedContext == null) {
                    response.outputHtml(host + context + "404 Not Refund");
                    socket.close();
                    return;
                }
                Map<String, MappedWrapper> wrappers = mappedContext.getWrappers();
                MappedWrapper mappedWrapper = wrappers.get(url);
                if (mappedWrapper == null) {
                    response.outputHtml(url + "404 Not Refund");
                    socket.close();
                    return;
                }
                Servlet servlet = mappedWrapper.getWrapper().getServlet();
                if (servlet == null) {
                    response.outputHtml(url + "403 Request Forbidden");
                    socket.close();
                    return;
                }
                servlet.service(request, response);
                socket.close();
            }
        }catch (Exception e) {
            e.printStackTrace();
        }
    }
}
